package cn.school.demo.ui.history

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentHistoryViewPageBinding
import cn.school.demo.pojo.ArticleBrowse
import com.blankj.utilcode.util.LogUtils
import com.mylhyl.circledialog.CircleDialog
import java.time.LocalTime


class HistoryViewPageFragment : Fragment() {

    private lateinit var binging: FragmentHistoryViewPageBinding
    private lateinit var viewModel: HistoryViewModel
    private lateinit var list: MutableList<ArticleBrowse>

    companion object {
        fun newInstance() = HistoryViewPageFragment()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this).get(HistoryViewModel::class.java)
        binging =
            DataBindingUtil.inflate(inflater, R.layout.fragment_history_view_page, container, false)
        binging.lifecycleOwner = viewLifecycleOwner
        binging.vw = this
        init()
        return binging.root
    }

    @SuppressLint("NotifyDataSetChanged", "NewApi")
    private fun init() {
        binging.historyFragmentDelete.visibility = View.VISIBLE
        viewModel.apply {
            browser.observe(viewLifecycleOwner) {
                LogUtils.e(LocalTime.now().toString())
                viewModel.browser.value?.let {
                    LogUtils.d("我竟来了！", it.size)
                    if (it.isNotEmpty() && it.size > 0)
                        binging.historyFragmentRecyclerview.apply {
                            binging.historyArticleProgressBar.visibility = View.GONE
                            list = it
                            this.adapter = ArticleBrowseAdapter(list)
                            this.layoutManager =
                                LinearLayoutManager(requireContext())//不设置的话不知道用什么布局
                            binging.historyFragmentRecyclerviewNoData.visibility = View.GONE
                            binging.historyFragmentAllDeleteText.isEnabled = true
                        } else binging.apply {
                        historyFragmentRecyclerview.visibility = View.GONE
                        historyFragmentRecyclerviewNoData.visibility = View.VISIBLE
                        historyArticleProgressBar.visibility = View.GONE
                        binging.historyFragmentAllDeleteText.isEnabled = false
                    }
                }
            }
            choose.observe(viewLifecycleOwner) { deleteUI() }
        }
        MyApplication.apply {
            historyEditOrSave.observe(viewLifecycleOwner) {
                when (it) {
                    true -> {
                        binging.historyFragmentDelete.visibility = View.VISIBLE
                    }
                    else -> {
                        binging.historyFragmentDelete.visibility = View.GONE
                        viewModel.clearChoose()
                    }
                }
            }
            isDelete.observe(viewLifecycleOwner) {
                if (it) {
                    viewModel.delete(isAll)
                    viewModel.result.observe(viewLifecycleOwner) {
                        if (it) {
                            historyEditOrSave.value = false
                            val v = viewModel.getBrowseHistory()
                            v.observe(viewLifecycleOwner) {
                                if (it.isEmpty()) {
                                    binging.historyFragmentRecyclerviewNoData.visibility =
                                        View.VISIBLE
                                    binging.historyFragmentAllDeleteText.apply {
                                        isEnabled = false
                                        setTextColor(
                                            resources.getColorStateList(
                                                R.color.text_gray,
                                                null
                                            )
                                        )
                                    }
                                } else {
                                    binging.historyFragmentRecyclerviewNoData.visibility = View.GONE
                                    binging.historyFragmentAllDeleteText.apply {
                                        isEnabled = true
                                        setTextColor(
                                            resources.getColorStateList(
                                                R.color.black,
                                                null
                                            )
                                        )
                                    }
                                }
                                list.clear()
                                list.addAll(it)
                                binging.historyFragmentRecyclerview.adapter!!.notifyDataSetChanged()
                            }
                        }
                    }
                }
            }
        }
    }

    private fun deleteUI() {
        LogUtils.e("我竟来了")
        when (viewModel.choose.value!!.size) {
            0 -> binging.historyFragmentDeleteText.apply {
                isEnabled = false
                text = "删除"
                setTextColor(resources.getColorStateList(R.color.text_gray, null))
            }
            else -> {
                val text = SpannableString("删除(${viewModel.choose.value!!.size})")
                text.setSpan(
                    ForegroundColorSpan(Color.parseColor("#000000")),
                    0,
                    2,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                text.setSpan(
                    ForegroundColorSpan(Color.parseColor("#ff0000")),
                    2,
                    text.length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                binging.historyFragmentDeleteText.apply {
                    isEnabled = true
                    this.text = text
                }
            }
        }
    }

    fun deleteAll() {
        CircleDialog.Builder().setText("是否删除所有内容？删除后不可再找回！").setPositive("确定") {
            MyApplication.apply {
                isAll = true
                isDelete.value = true
            }
        }.setNegative("取消") {
            MyApplication.apply {
                isAll = true
                isDelete.value = false
            }
        }.show(parentFragmentManager)
    }

    fun delete() {
        CircleDialog.Builder().setText("是否删除当前${viewModel.choose.value!!.size}篇内容")
            .setPositive("确定") {
                MyApplication.apply {
                    isAll = false
                    isDelete.value = true
                }
            }.setNegative("取消") {
                MyApplication.apply {
                    isAll = false
                    isDelete.value = false
                }
            }
            .show(parentFragmentManager)
    }

    private inner class ArticleBrowseDateHolder(view: View) : RecyclerView.ViewHolder(view),
        View.OnClickListener {
        private lateinit var articleBrowse: ArticleBrowse
        private val textView =
            itemView.findViewById<TextView>(R.id.history_recycler_date_view_text)

        init {
            itemView.setOnClickListener(this)
        }

        @SuppressLint("SetTextI18n")
        fun bind(articleBrowse: ArticleBrowse) {
            this.articleBrowse = articleBrowse
            textView.text =
                "${this.articleBrowse.time.browseTime}浏览${this.articleBrowse.time.frequency}条内容"
        }

        override fun onClick(p0: View?) {
            LogUtils.d("你别点我了，点我没效果！！")
        }
    }

    private inner class ArticleBrowseHolder(view: View) : RecyclerView.ViewHolder(view),
        View.OnClickListener {
        private lateinit var articleBrowse: ArticleBrowse
        private val titleTextView =
            itemView.findViewById<TextView>(R.id.history_recycler_view_text)
        private val button =
            itemView.findViewById<ImageButton>(R.id.history_recycler_view_chip)

        init {
            itemView.setOnClickListener(this)
        }

        @SuppressLint("NewApi")
        fun bind(articleBrowse: ArticleBrowse, position: Int) {
            this.articleBrowse = articleBrowse
            titleTextView.text = this.articleBrowse.article!!.articleName
            MyApplication.historyEditOrSave.observe(viewLifecycleOwner) {
                when (it) {
                    true -> {
                        button.visibility = View.VISIBLE
                    }
                    else -> {
                        button.visibility = View.GONE
                        button.setBackgroundResource(R.drawable.circle_unselected)
                        this.articleBrowse.isDelete = false
                    }
                }
            }
            //按钮未选中
            button.setOnClickListener {
                if (viewModel.choose.value!!.contains(position)) { //按钮以选中状态
                    it.setBackgroundResource(R.drawable.circle_unselected)
                    this.articleBrowse.isDelete = false
                    viewModel.removeChoose(position)
                } else {
                    it.setBackgroundResource(R.drawable.circle_selected)
                    this.articleBrowse.isDelete = true
                    viewModel.addChoose(position)
                }
            }
        }

        override fun onClick(v: View) {
            LogUtils.d("无效果！")
            MyApplication.apply {
                article = this@ArticleBrowseHolder.articleBrowse.article
                navigateThing["ArticleEntity"] = R.id.action_ArticleEntity_to_History.toString()
                goto(
                    R.id.action_History_to_ArticleEntity,
                    findNavController(),
                    parentFragmentManager
                )
            }
        }
    }

    private inner class ArticleBrowseAdapter(var articleBrowseList: MutableList<ArticleBrowse>) :
        RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        private val DATE_VIEW = 1
        private val ARTICLE_VIEW = 2

        override fun getItemViewType(position: Int): Int {
            return if (articleBrowseList[position].article == null) DATE_VIEW else ARTICLE_VIEW
        }

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): RecyclerView.ViewHolder {
            return when (viewType) {
                DATE_VIEW -> {
                    val view =
                        layoutInflater.inflate(R.layout.list_item_history_date, parent, false)
                    ArticleBrowseDateHolder(view)
                }
                else -> {
                    val view = layoutInflater.inflate(R.layout.list_item_history, parent, false)
                    ArticleBrowseHolder(view)
                }
            }
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val articleBrowse = articleBrowseList[position]
            when (getItemViewType(position)) {
                DATE_VIEW -> (holder as ArticleBrowseDateHolder).bind(articleBrowse)
                ARTICLE_VIEW -> (holder as ArticleBrowseHolder).bind(articleBrowse, position)
            }
        }

        override fun getItemCount() = articleBrowseList.size

    }
}